package com.xj.openapi4j.service.token;

import com.alibaba.fastjson.JSONObject;
import com.xj.util.Constance;
import com.xj.openapi4j.util.RequestTool;
import com.xj.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;


@Service
@Slf4j
public class U8Token {
    @Value("${u8AppKey}")
    String u8AppKey;

    @Value("${u8AppSecret}")
    String u8AppSecret;

    @Value("${u8ApiUrl}")
    String u8ApiUrl;

    @Value("${fromAccount}")
    String  from_account;
    @Autowired
    RedisTemplate  redisTemplate;


    public String   reGetToken() throws Exception {
        Map map = new HashMap<>();
        map.put("from_account", from_account);
        map.put("app_key",u8AppKey);
        map.put("app_secret",u8AppSecret);
        String str = RequestTool.doGet(u8ApiUrl, map);
        JSONObject jsonObject=  JSONObject.parseObject(str);
        if(jsonObject.getIntValue("errorcode")!=0){
            throw  new Exception(jsonObject.getString("errmsg"));
        }
        JSONObject tokenObject=  jsonObject.getJSONObject("token");
        Integer  expiresIn=tokenObject.getIntValue("expiresIn");
        String  token=tokenObject.getString("id");
        log.info(token);
        redisTemplate.opsForValue().set(Constance.u8token,token, Duration.ofSeconds(expiresIn));
        return token;
    }


    public  String  getToken()  throws  Exception{
      Boolean isExist=   redisTemplate.hasKey(Constance.u8token);
      if(!isExist){
          reGetToken();
      }
      String token=(String)  redisTemplate.opsForValue().get(Constance.u8token);
      if(StringUtils.isNotEmpty(token)){
          return  token;
      }else {
          throw  new Exception("获取u8api token失败");
      }

    }

}
